package com.yxy.controller.service;

import com.yxy.common.Const;
import com.yxy.common.ServerResponse;
import com.yxy.common.enums.SportTypeEnum;
import com.yxy.entity.Sport;
import com.yxy.entity.User;
import com.yxy.jpush.Jpush;
import com.yxy.util.DateUtils;
import org.apache.commons.lang.StringUtils;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import com.yxy.dto.SportModel;
import com.yxy.service.SportService;


/**
 * SportController控制器类
 * Sport
 * Sport
 * Sport
 * Sport
 *
 * @version <pre>
 * Author	Version		Date		Changes
 * 邓文俊    1.0  2018-01-11 16:00:41 Created
 *  </pre>
 * @since 1.
 */
@Controller
@RequestMapping("/service/sports")
public class SportController {

    public Logger logger = LoggerFactory.getLogger(SportController.class);

    @Autowired
    private SportService sportService;


    //列表
    @RequestMapping(value = "list", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<List<SportModel>> list() throws Exception{
        List<SportModel> sportModelList= new ArrayList<SportModel>();
        List<Sport> sportList = sportService.findAll();
        if(sportList!=null && sportList.size()>0){
            for (Sport sport:sportList) {
                SportModel sportModel = entityToModel(sport);
                sportModelList.add(sportModel);
            }
        }
        return ServerResponse.createBySuccess("查询成功",sportModelList);
    }

    //添加
    @RequestMapping(value = "create", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<SportModel> cerate(@RequestBody SportModel sportModel, HttpServletRequest request){
        Sport sport = modelToEntity(sportModel);
        if(sport!=null){
            setTemplateDateAndUser(sport,request);
            if(sportService.create(sport)){


                return ServerResponse.createBySuccessMessage("添加成功");
            }
        }
        return ServerResponse.createByErrorMessage("操作失败,请重试");
    }

    //删除
    @RequestMapping("delete")
    @ResponseBody
    public ServerResponse delete(Integer id,HttpServletRequest request) throws Exception{
        Sport sport = new Sport();
        sport.setId(id);
        setTemplateDateAndUser(sport,request);
        if(sportService.delete(sport)){
            return ServerResponse.createBySuccessMessage("删除成功");
        }
        return ServerResponse.createByErrorMessage("操作失败，请重试！");
    }

    //查询活动
    @RequestMapping("findOne")
    @ResponseBody
    public ServerResponse findOne(Integer id)throws Exception{
        Sport sport = sportService.findByPK(id);
        if (sport!=null){
            SportModel sportModel = entityToModel(sport);
            return ServerResponse.createBySuccess("查询成功",sportModel);
        }
        return ServerResponse.createByErrorMessage("操作失败，请重试！");
    }

    //修改
    @RequestMapping(value = "update", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<SportModel> update(@RequestBody SportModel sportModel,HttpServletRequest request){
        Sport sport = modelToEntity(sportModel);

        setTemplateDateAndUser(sport,request);
        if(sportService.update(sport)){
            return ServerResponse.createBySuccessMessage("操作成功!");
        }
        return ServerResponse.createByErrorMessage("操作失败,请重试!");
    }

    //模糊查询
    @RequestMapping(value = "findLikeList", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse findLikeList(SportModel sportModel) throws Exception{
        Sport sport = modelToEntity(sportModel);
        List<Sport> sportList = sportService.findLikeList(sport);
        List<SportModel> sportModelList =new ArrayList<SportModel>();
        if (sportList!=null && sportList.size()>0){
            for (Sport s:sportList) {
                SportModel model = entityToModel(sport);
                sportModelList.add(model);
            }

        }
        return ServerResponse.createBySuccess("查询成功",sportModelList);
    }






    /**
     * 统一设置 Date 和 修改用户
     *
     * @param entity
     */
    private void setTemplateDateAndUser(Sport entity, HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");

        if (entity == null) {
            logger.error("ERR:Date set error.");
            return;
        }
        if (entity.getId() == null && entity.getCreateTime() == null) {
            //如果id为空， 就是新建
            entity.setCreateTime(new Date());
            entity.setCreateBy(user.getUsername());
        } else {

            if (entity.getUpdateTime() == null) {
                entity.setUpdateTime(new Date());
            }
            if (entity.getUpdateBy() == null && user != null) {
                entity.setUpdateBy(user.getUsername());
            }
        }
    }


    /**
     * 复制 数据库端 Entity 到 前端 Entity
     *
     * @param entity 数据库端 Entity
     * @return model  前端 Model
     */
    public SportModel entityToModel(Sport entity) throws Exception {
        if (entity == null) {
            return new SportModel();
        }
        SportModel model = new SportModel();
        if (entity.getSportStartDatetime() != null) {
            model.setSportStartDatetime(DateUtils.formatDateTime(entity.getSportStartDatetime()));
        }
        if (entity.getSportEndDatetime() != null) {
            model.setSportEndDatetime(DateUtils.formatDateTime(entity.getSportEndDatetime()));
        }
        if (entity.getCreateTime() != null) {
            model.setCreateTime(DateUtils.formatDateTime(entity.getCreateTime()));
        }
        if (entity.getUpdateTime() != null) {
            model.setUpdateTime(DateUtils.formatDateTime(entity.getUpdateTime()));
        }
        if (entity.getPhone() != null) {
            model.setPhone(String.valueOf(entity.getPhone()));
        }
        if (entity.getDelFlag() != null) {
            model.setDelFlag(String.valueOf(entity.getDelFlag()));
        }
        if (entity.getId() != null) {
            model.setId(String.valueOf(entity.getId()));
        }
        if (entity.getPubUserId() != null) {
            model.setPubUserId(String.valueOf(entity.getPubUserId()));
        }
        if (entity.getSportRealJoinPersonNum() != null) {
            model.setSportRealJoinPersonNum(String.valueOf(entity.getSportRealJoinPersonNum()));
        }
        if (entity.getYxySportExtend4() != null) {
            model.setYxySportExtend4(String.valueOf(entity.getYxySportExtend4()));
        }
        if (entity.getPubSportTypeId() != null) {
            model.setPubSportTypeId(String.valueOf(entity.getPubSportTypeId()));
        }
        if (entity.getSportAllowJoinPersonNum() != null) {
            model.setSportAllowJoinPersonNum(String.valueOf(entity.getSportAllowJoinPersonNum()));
        }
        if (entity.getPubSportStatus() != null) {
            model.setPubSportStatus(String.valueOf(entity.getPubSportStatus()));
        }
        if (StringUtils.isNotBlank(entity.getPubSportTitle())) {
            model.setPubSportTitle(String.valueOf(entity.getPubSportTitle()));
        }
        if (StringUtils.isNotBlank(entity.getPubSportImg())) {
            model.setPubSportImg(String.valueOf(entity.getPubSportImg()));
        }
        if (StringUtils.isNotBlank(entity.getPubSportDes())) {
            model.setPubSportDes(String.valueOf(entity.getPubSportDes()));
        }
        if (StringUtils.isNotBlank(entity.getPubSportTypeName())) {
            model.setPubSportTypeName(String.valueOf(entity.getPubSportTypeName()));
        }
        if (StringUtils.isNotBlank(entity.getPubSportPlace())) {
            model.setPubSportPlace(String.valueOf(entity.getPubSportPlace()));
        }
        if (StringUtils.isNotBlank(entity.getUpdateBy())) {
            model.setUpdateBy(String.valueOf(entity.getUpdateBy()));
        }
        if (StringUtils.isNotBlank(entity.getCreateBy())) {
            model.setCreateBy(String.valueOf(entity.getCreateBy()));
        }
        if (StringUtils.isNotBlank(entity.getSportTypeImg())) {
            model.setSportTypeImg(String.valueOf(entity.getSportTypeImg()));
        }

        if(StringUtils.isNotBlank(entity.getUserFace())){
            model.setUserFace(String.valueOf(entity.getUserFace()));
        }
        if(StringUtils.isNotBlank(entity.getNickname())){
            model.setNickName(String.valueOf(entity.getNickname()));
        }
        if(entity.getSportEndDatetime()!=null){
//            int a =entity.getSportEndDatetime().compareTo(new Date());
            if(entity.getSportEndDatetime().after(new Date())){
                if(entity.getSportFlag()==null&&entity.getSportRealJoinPersonNum()==entity.getSportAllowJoinPersonNum()){
                    model.setSportFlag(Const.SportFlag.SPORT_FLAG_PERSON_FULL);
                }else {
                    if(entity.getSportFlag()!=null){
                        model.setSportFlag(entity.getSportFlag());
                    }else {
                        model.setSportFlag(Const.SportFlag.SPORT_FLAG_I_WANT_JOIN);
                    }

                }
            }else {
                model.setSportFlag(Const.SportFlag.SPORT_FLAG_END);
            }
        }
        if(entity.getSportStartWeek()!=null){
            model.setSportStartWeek(String.valueOf(entity.getSportStartWeek()));
        }
        if(entity.getSportEndWeek()!=null){
            model.setSportEndWeek(String.valueOf(entity.getSportEndWeek()));
        }
        if(entity.getDiscussNum()!=null){
            model.setDiscussNum(String.valueOf(entity.getDiscussNum()));
        }
        if(entity.getBrowseNum()!=null){
            model.setBrowseNum(String.valueOf(entity.getBrowseNum()));
        }
        if(entity.getSex()!=null){
            model.setSex(String.valueOf(entity.getSex()));
        }

        if(entity.getUserPhone()!=null){
            model.setUserPhone(entity.getUserPhone());
        }
        if(entity.getUserId()!=null){
            model.setUserId(String.valueOf(entity.getUserId()));
        }
        return model;
    }

    /**
     * 复制前端 Model 到 数据库端 Entity
     *
     * @param model 前端 Model
     * @return entity 数据库端 Entity
     */
    public Sport modelToEntity(SportModel model) {
        if (model == null) {
            return new Sport();
        }
        Sport entity = new Sport();
        if (StringUtils.isNotBlank(model.getSportStartDatetime())) {
            entity.setSportStartDatetime(DateUtils.parseDate(model.getSportStartDatetime()));
        }
        if (StringUtils.isNotBlank(model.getSportEndDatetime())) {
            entity.setSportEndDatetime(DateUtils.parseDate(model.getSportEndDatetime()));
        }
        if (StringUtils.isNotBlank(model.getCreateTime())) {
            entity.setCreateTime(DateUtils.parseDate(model.getCreateTime()));
        }
        if (StringUtils.isNotBlank(model.getUpdateTime())) {
            entity.setUpdateTime(DateUtils.parseDate(model.getUpdateTime()));
        }
        if (StringUtils.isNotBlank(model.getPhone())) {
            entity.setPhone(String.valueOf(model.getPhone()));
        }
        if (StringUtils.isNotBlank(model.getDelFlag())) {
            entity.setDelFlag(Integer.parseInt(model.getDelFlag()));
        }
        if (StringUtils.isNotBlank(model.getId())) {
            entity.setId(Integer.parseInt(model.getId()));
        }
        if (StringUtils.isNotBlank(model.getPubUserId())) {
            entity.setPubUserId(Integer.parseInt(model.getPubUserId()));
        }
        if (StringUtils.isNotBlank(model.getSportRealJoinPersonNum())) {
            entity.setSportRealJoinPersonNum(Integer.parseInt(model.getSportRealJoinPersonNum()));
        }
        if (StringUtils.isNotBlank(model.getYxySportExtend4())) {
            entity.setYxySportExtend4(Integer.parseInt(model.getYxySportExtend4()));
        }
        if (StringUtils.isNotBlank(model.getPubSportTypeId())) {
            String sportTypeId = model.getPubSportTypeId();
            //通过枚举类获取运动类型名称
            entity.setPubSportTypeName(SportTypeEnum.getValues(sportTypeId).getSportTypeName());
            entity.setPubSportImg(SportTypeEnum.getValues(sportTypeId).getSportTypeBgImg());
            entity.setSportTypeImg(SportTypeEnum.getValues(sportTypeId).getSportTypeImg());
            entity.setPubSportTypeId(Integer.parseInt(model.getPubSportTypeId()));
        }
        if (StringUtils.isNotBlank(model.getSportAllowJoinPersonNum())) {
            entity.setSportAllowJoinPersonNum(Integer.parseInt(model.getSportAllowJoinPersonNum()));
        }
        if (StringUtils.isNotBlank(model.getPubSportStatus())) {
            entity.setPubSportStatus(Integer.parseInt(model.getPubSportStatus()));
        }
        entity.setPubSportTitle(model.getPubSportTitle());
        entity.setPubSportImg(model.getPubSportImg());
        entity.setPubSportDes(model.getPubSportDes());
        entity.setPubSportPlace(model.getPubSportPlace());
        entity.setUpdateBy(model.getUpdateBy());
        entity.setCreateBy(model.getCreateBy());
        entity.setSportTypeImg(model.getSportTypeImg());

        return entity;
    }

}